package com.zdxlz.fcmp.common.security.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zdxlz.fcmp.common.core.constant.enums.ResCode;
import com.zdxlz.fcmp.common.core.exception.BizException;
import com.zdxlz.fcmp.upms.api.entity.SystemUser;
import com.zdxlz.fcmp.upms.api.mapper.SystemMenuMapper;
import com.zdxlz.fcmp.upms.api.mapper.SystemUserMapper;
import com.zdxlz.fcmp.upms.api.mapper.SystemUserRoleMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * Security安全认证框架默认用户详情接口实现类
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Autowired
    private SystemMenuMapper systemMenuMapper;

    @Resource
    private SystemUserRoleMapper systemUserRoleMapper;

    /**
     * 通过【用户名称】查询用户对象信息
     */
    @Override
    public UserDetails loadUserByUsername(String mobile) throws UsernameNotFoundException {
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getMobile, mobile);

        SystemUser user = systemUserMapper.selectOne(queryWrapper);
        // 用户不存在
        if (ObjectUtil.isEmpty(user))
            throw new BizException(ResCode.ERROR_USER_NOT_EXIST.getCode(), ResCode.ERROR_USER_NOT_EXIST.getReason());

        // 用户被停用
        if (!user.getStatus())
            throw new BizException(ResCode.ERROR_USER_DISABLED.getCode(), ResCode.ERROR_USER_DISABLED.getReason());

        // 获取用户菜单权限标识
        // List<String> permissions = List.of("USER", "SUPPER");
        List<String> userPermissions = systemMenuMapper.getPermissionByUserId(user.getId());

        // 获取用户角色
        List<String> roleCodes = systemUserRoleMapper.getUserRoleByUserId(user.getId());

        return new SystemUserLoginDetail(user, userPermissions, roleCodes);
    }

}
